﻿using fastdb.Common;

namespace fastdb.Db.storage;

/// <summary>
///     每页大小是4KB
/// </summary>
public struct Page
{
    /// <summary>
    /// 页序号
    /// </summary>
    public int PageNo { get; set; }

    public int PrePageNode { get; set; }

    public int NextPageNode { get; set; }

    public byte[] ContentBytes { get; set; }


    public byte[] GenerateBytes()
    {
        var headerBytes = ByteHelper.ByteArrayJoin(BitConverter.GetBytes(PageNo), BitConverter.GetBytes(PrePageNode),
            BitConverter.GetBytes(NextPageNode), new byte[96 - 12]);
        var res = ByteHelper.ByteArrayJoin(headerBytes, ContentBytes);

        return res;
    }

    public bool LoadFromBytes(byte[] bytes)
    {
        PageNo = ByteHelper.GetNumberFromBytes(bytes.Skip(0).Take(4).ToArray());
        PrePageNode = ByteHelper.GetNumberFromBytes(bytes.Skip(4).Take(4).ToArray());
        NextPageNode = ByteHelper.GetNumberFromBytes(bytes.Skip(12).Take(4).ToArray());
        ContentBytes = bytes.Skip(96).Take(4000).ToArray();

        return true;
    }
}